import React, { Component } from 'react';
import axiosIns from '../../utils/axios';
import { codeStyle } from '../../utils/commonStyle';
export default class SendCode extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tagValue: '获取验证码',
      disable: false
    };
  }
  componentDidMount() {
    // if (this.props.phone) {
    //     this.setState({
    //         disable: false,
    //         phoneDisdbled: true
    //     })
    // }
  }
  _sendCode() {
    const { phone, disablePhone } = this.props;
    if (this.state.disable) {
      return;
    } else {
      if (!phone.toString().match('^[1][34578][0-9]{9}$')) {
        //模态框
        return;
      }
      this.setState({
        tagValue: '发送中...',
        disable: true
        // phoneDisdbled: true
      });
      if (disablePhone) {
        disablePhone(true);
      }

      this._getCode();
    }
  }
  _getCode() {
    //后端获取验证码
    const { api, phone } = this.props;
    // const res = axiosIns(api);
    // if(res.status ==200) {
    setTimeout(() => {
      this._tagTimer();
    }, 500);
    // }
    // fetch.request(`${api}`, 'GET', { phone: phone }).then(res => {
    //     console.log(res)
    //     console.log(res.code.statuCode == CODE.SUCCESS)
    //     if (res.code.statuCode == CODE.SUCCESS) {
    //         setTimeout(() => {
    //             this._tagTimer();
    //         }, 500)

    //     } else if (res.code.statuCode == CODE.VERIFICATION_CODE_TIME_OUT) {
    //         modal.showError("获取验证码服务端网络超时")
    //     }
    // }).catch(e => {

    // })
  }

  //倒数计时器
  _tagTimer() {
    let time = 180;
    console.log(time);
    const mytimer = setInterval(() => {
      time--;
      if (time > 0) {
        this.setState({
          tagValue: '获取(' + time + ')'
        });
      } else {
        const { disablePhone } = this.props;
        if (disablePhone) {
          disablePhone(false);
        }
        this.setState({
          // phoneDisdbled: false,
          disable: false,
          tagValue: '获取验证码'
        });
        clearInterval(mytimer);
      }
    }, 1000);
  }

  render() {
    //手机号 api 发送验证码成功期间后手机号不可更改
    const { codeStyle } = this.props;
    const { disable } = this.state;
    return (
      <a
        className="vaildCode"
        style={{
          color: disable ? '#d8d8d8' : '#556fb5',
          borderColor: disable ? '#d8d8d8' : '#556fb5',
          ...codeStyle
        }}
        onClick={() => this._sendCode()}
      >
        {this.state.tagValue}
      </a>
    );
  }
}
